<template>
    <div>
        <el-dialog v-model="dialogVisible" width="80%" align-center :show-close="false" @close="handleClose" draggable destroy-on-close>
            <template #header="{ close }">
                <div class="dialog-header flex justify-between items-center">
                    <div>经费认领</div>
                    <el-icon class="el-icon--left cursor-pointer" @click="close">
                        <CircleCloseFilled color="#fff" />
                    </el-icon>
                </div>
            </template>

            <div class="bg-white my-[10px]">
                <BaseHead>来款信息</BaseHead>
                <BaseTable>
                    <tr>
                        <td class="td-name">摘要</td>
                        <td colspan="3">{{cwIncomeShow.note}}</td>
                    </tr>
                    <tr>
                        <td class="td-name">来款金额</td>
                        <td>{{FloatDiv(cwIncomeShow.feeValue,10000)}}<span> 万元</span></td>
                        <td class="td-name">来款类型</td>
                        <td>
                            <CommonLabel :dataList="incomeTypeList" valueKey="code" :value="cwIncomeShow.incomeType" />
                        </td>
                    </tr>
                    <tr>
                        <td class="td-name">可认金额</td>
                        <td>{{FloatDiv(cwIncomeShow.notClaimfee,10000) }}<span> 万元</span></td>
                        <td class="td-name">来款时间</td>
                        <td>{{cwIncomeShow.incomeDate}}</td>
                    </tr>
                </BaseTable>
            </div>
            <div class="bg-white my-[10px]">
                <BaseHead style="border-bottom: 0">项目信息</BaseHead>
                <div class="p-[10px]">
                    <el-form :model="claimProjectShow" label-width="130px" ref="claimProjectShowRef">
                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="项目名称">
                                    <el-select ref="selectRef"  v-model="claimProjectShow.projectName" clearable
                                         popper-class="t-select-table" filterable
                                        :filter-method="getprojectList">
                                        <el-table :data="projectList" style="width: 100%" @row-click="handleRowClick">
                                            <el-table-column prop="code" label="项目编号" width="130" />
                                            <el-table-column prop="name" :show-overflow-tooltip="true" label="项目名称" />
                                            <el-table-column prop="chargerName" label="负责人" width="80" />
                                            <el-table-column prop="account" label="负责人工号" width="110" />
                                        </el-table>

                                        <el-option v-show="false" v-for="item in projectList" :key="item.projectId"
                                            :label="item.name" :value="item.projectId">
                                        </el-option>
                                        <template #footer><span
                                                style="padding:5px 10px;background-color:#f0f0f0">注：已显示满足条件的前50条记录</span></template>
                                    </el-select>

                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="负责人">
                                    {{claimProjectShow.chargerName}}
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="项目未到账金额"> {{claimProjectShow.notIncomeFee}}<span> 万元</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="项目合同金额">
                                    {{claimProjectShow.projectFeeInfo}}
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
            </div>
            <div class="bg-white my-[10px]">
                <BaseHead style="border-bottom: 0">认领经费</BaseHead>
                <el-form :model="claimShow" label-width="130px" ref="claimShowRef">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="认领金额(万元)" prop="claimFee">
                                <el-input v-model="claimShow.claimFee" style="width: 90%" clearable
                                    @input="e => checkclaimFee(e)">
                                </el-input>
                                <span v-show="showclaimFee" class="remark">{{claimFeeShow.claimFeeInfo}}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item v-show="showIncomeType" label="来款类型" prop="incomeType">
                                <el-radio-group v-model="claimShow.incomeType">
                                    <el-radio v-for="item in incomeTypeList" :key="item.code" :value="item.code"
                                        size="large">{{
                                        item.name }}</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="外拨金额(万元)" prop="outboundFee">
                                <el-input v-model="claimShow.outboundFee" style="width: 90%" clearable
                                    @input="e => checkoutboundFee(e)">
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="留校经费(万元)" prop="schoolFee">
                                <span class="remark">{{claimShow.schoolFee}}</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item v-show="showNewCardFlag" label="是否需要建新卡" prop="createNewCardFlag">
                                <el-radio-group v-model="claimFeeShow.createNewCardFlag">
                                    <el-radio value="1" size="large">是</el-radio>
                                    <el-radio value="0" size="large">否</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>

                    </el-row>
                </el-form>
            </div>
            <div class="bg-white my-[10px]" v-show="cardShow">
                <BaseHead style="border-bottom: 0">建卡及额度</BaseHead>
                <BaseTable>
                    <tr>
                        <td class="td-name">经费卡负责人</td>
                        <td colspan="3" v-for="(items,index) in claimFeeShow.claimIncomeFeeShow" :key="index">
                            {{items.feeChargerName+"("+items.feeChargerCode+")"}}</td>
                    </tr>
                    <tr>
                        <td class="td-name">所属单位</td>
                        <td colspan="3" v-for="(items,index) in claimFeeShow.claimIncomeFeeShow" :key="index">
                            <el-select v-model="items.unitId" clearable style="width: 30%;">
                                <el-option v-for="item in unitIdList" :key="item.codeColumn" :label="item.valueColumn"
                                    :value="item.codeColumn" />
                            </el-select>
                        </td>
                    </tr>
                    <tr>
                        <td class="td-name">经费卡号</td>
                        <td colspan="3" v-for="(items,index) in claimFeeShow.claimIncomeFeeShow" :key="index">
                            {{items.feeCardNum?items.feeCardNum:"审核通过后自动生成"}}
                        </td>
                    </tr>
                    <tr>
                        <td class="td-name">留校经费(万元)</td>
                        <td colspan="3" v-for="(items,index) in claimFeeShow.claimIncomeFeeShow" :key="index">
                            {{items.schoolFee}}</td>
                    </tr>
                    <tr>
                        <td class="td-name">外拨经费(万元)</td>
                        <td colspan="3" v-for="(items,index) in claimFeeShow.claimIncomeFeeShow" :key="index">
                            {{items.outboundFee}}</td>
                    </tr>
                </BaseTable>
            </div>
            <div class="bg-white my-[10px]">
                <div style="line-height:50px;" v-show="budgetSplitShow">
                    <span style="margin: 20px;">请确认额度拆分方式： </span>
                    <el-radio-group v-model="claimShow.budgetSplitModde">
                        <el-radio value="liuxiaoBudgetSplit" size="large"
                            @click.native.prevent='handleSplitModde("liuxiaoBudgetSplit")'>拆分总留校额度</el-radio>
                        <el-radio value="incomeBudgetSplit" size="large"
                            @click.native.prevent='handleSplitModde("incomeBudgetSplit")'>拆分本次入账额度</el-radio>
                    </el-radio-group>
                </div>
                <BaseTable v-if="claimShow.budgetSplitModde =='liuxiaoBudgetSplit' && budgetshow">
                    <tr>
                        <td class="td-subname"></td>
                        <td class="td-subname"></td>
                        <td class="td-subname" colspan="6" v-for="(items,index) in claimFeeShow.claimIncomeFeeShow"
                            :key="index">
                            {{items.feeChargerName+"("+items.feeChargerCode+")"}}</td>
                    </tr>
                    <tr>
                        <td class="td-subname">额度名称</td>
                        <td class="td-subname">留校总额度(万元)</td>
                        <td class="td-subname" colspan="6">额度拆分详情(万元)</td>
                    </tr>
                    <tr v-for="(items,index) in claimFeeShow.claimBudgetFeeShow" :key="index">
                        <td class="td-subname">{{items.subjectName}}</td>
                        <td class="td-subname">{{items.subjectFee}}</td>
                        <td colspan="3" v-for="(item,index) in items.claimSubBudgetFeeShow" :key="index">
                            {{item.budgetFee}}
                        </td>
                    </tr>
                </BaseTable>
                <BaseTable v-if="claimShow.budgetSplitModde =='incomeBudgetSplit' && budgetshow">
                    <tr>
                        <td class="td-subname"></td>
                        <td class="td-subname"></td>
                        <td class="td-subname" colspan="6" v-for="(items,index) in claimFeeShow.claimIncomeFeeShow"
                            :key="index">
                            {{items.feeChargerName+"("+items.feeChargerCode+")"}}</td>
                    </tr>
                    <tr>
                        <td class="td-subname">额度名称</td>
                        <td class="td-subname">留校总额度(万元)</td>
                        <td class="td-subname" colspan="3">累计入账额度(万元)</td>
                        <td class="td-subname" colspan="3">本次额度拆分(万元)</td>
                    </tr>
                    <tr v-for="(items,index) in claimFeeShow.claimBudgetFeeShow" :key="index">
                        <td class="td-subname">{{items.subjectName}}</td>
                        <td class="td-subname">{{items.subjectFee}}</td>
                        <td colspan="3" v-for="(item,index) in items.claimSubBudgetFeeShow" :key="index">
                            {{item.splitBudgetFee}}
                        </td>
                        <td colspan="3" v-for="(item,index) in items.claimSubBudgetFeeShow" :key="index">
                            <el-input v-if="items.subjectName != '合计' && items.hasChildren == '0'" v-model="item.budgetFee" style="width: 90%"
                                clearable @input="checkbudgetFee(item, items)">
                            </el-input>
                            <el-input v-else disabled v-model="item.budgetFee"></el-input>
                        </td>
                    </tr>
                </BaseTable>
            </div>
            <div class="bg-white my-[10px]">
                <BaseTable v-show="manageShow">
                    <tr>
                        <td class="td-subname"></td>
                        <td class="td-subname"></td>
                        <td class="td-subname" colspan="6" v-for="(items,index) in claimFeeShow.claimIncomeFeeShow"
                            :key="index">
                            {{items.feeChargerName+"("+items.feeChargerCode+")"}}</td>
                    </tr>
                    <tr>
                        <td class="td-subname">管理费信息</td>
                        <td class="td-subname">-</td>
                        <td class="td-subname" colspan="3">累计扣除管理费(万元)</td>
                        <td class="td-subname" colspan="3">本次扣除管理费(万元)</td>
                    </tr>
                    <tr v-for="(items,index) in claimFeeShow.claimManageFeeShow" :key="index">
                        <td class="td-subname">{{items.subjectName}}</td>
                        <td class="td-subname">-</td>
                        <td colspan="3" v-for="(item,index) in items.claimSubManageFee" :key="index">
                            {{item.splitManageFee}}
                        </td>
                        <td colspan="3" v-for="(item,index) in items.claimSubManageFee" :key="index">
                            <el-input v-model="item.subjectFee" style="width: 90%" clearable>
                            </el-input>
                        </td>
                    </tr>
                </BaseTable>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <div class="operate-btns">
                        <el-button type="primary" @click="save('-1')">暂存</el-button>
                        <el-button type="primary" v-equalRole="['biz_kyry']" @click="save('1')">提交</el-button>
                        <el-button type="primary" v-equalRole="['biz_kycgly']" @click="save('2')">保存并通过</el-button>
                        <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
                    </div>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import BaseTable from "@/views/fee/components/BaseTable.vue";
import CommonLabel from "@/views/fee/components/CommonLabel.vue";
import CommonRadio from "@/views/fee/components/CommonRadio.vue";
import { isNum } from "@/utils/validate";
import { isMoney,FloatSub,FloatAdd,FloatDiv,FloatMul } from "@/utils/pub";
import { ElMessage } from "element-plus";
import useCommonFetch from "@/hooks/useCommonFetch";
import {getprolist,checkproject,getClaimFeeInfo,getManage,getBudegt } from "@/api/fee/rz/yhdk/index.js";
import {addclaim } from "@/api/fee/rz/xmrzbl/index.js";
import { ref } from "vue";
const dialogVisible = ref(false);
const cwIncomeShow = ref({}); //来款信息
const claimProjectShow = ref({notIncomeFee:0}); //项目信息
const claimShow = ref({incomeType:"mixed",schoolFee:0,}); //认领经费
const claimFeeShow = ref({});//建卡费模块
const incomeTypeList = useCommonFetch("来款类型");
const projectList= ref([]);//项目list
const unitIdList = useCommonFetch("成果归属单位"); //所有单位; 
const { proxy } = getCurrentInstance();
var projectId = "";//项目号
var checkProjectResult = "";//项目检查情况;
const showNewCardFlag =ref(false);//是否建新卡
const showIncomeType = ref(true); //经费类型
const showclaimFee = ref(false); //可认领金额展示
const cardShow = ref(false);//建卡及额度展示
const manageShow = ref(false);//管理费展示
const budgetSplitShow = ref(false);//选择分割方式展示
const budgetshow = ref(false); //预算拆分科目展示
const selectRef = ref(null);//选中项目弹窗
// 认领
const claimAction = async (row) => {
  dialogVisible.value = true;
  cwIncomeShow.value = row;
  claimShow.value.cwIncomeId=row.id;
};
defineExpose({ claimAction });
const emit = defineEmits(["save-success"]);

//获取项目列表
const getprojectList = async (queryString) => {
    const params = {
        pageNum: 1,
        pageSize: 50, name: queryString,
        projectStatusId:0
    };
    try {
        const res = await getprolist(params);
        if (res.code == 200) {
            projectList.value = res.rows;
        }
    } catch (error) {
        console.log(error);
    }
}
onMounted(() => {
    getprojectList();
});

//选中项目
const handleRowClick = (row) =>{
    //先清空
    handleclear();
    projectId = row.projectId;
    checkprojectForm(row); //检查项目  
}

const handleclear =() =>{
    cardShow.value = false;//建卡及额度展示
    manageShow.value = false;//管理费展示
    budgetSplitShow.value = false;//选择分割方式展示
    budgetshow.value = false;
    projectId = "";
    claimProjectShow.value = {notIncomeFee:0}; //项目信息
    claimShow.value = {...{budgetSplitModde:"",cwIncomeId:claimShow.value.cwIncomeId,incomeType:"mixed",outboundFee:"",claimFee:""}};
    claimFeeShow.value = {claimIncomeFeeShow:[],
    claimBudgetFeeShow:[{subjectName:"",subjectFee:"",claimSubBudgetFeeShow:[]}],
    claimManageFeeShow:[{subjectName:"",claimSubManageFee:[]}],};//建卡费模块
}

//检查项目是否满足认领要求
const checkprojectForm = async (data)=>{
    var projectClass = data.projectClass;
    var checkProjectInfo = "";
    if (!projectId) {
        ElMessage.error("未选择要认领的项目！");
		return false;
	}
    let params= {projectId: projectId};
    try {
        const res = await checkproject(params);
        checkProjectResult = res;
        var checkBudgetFlag = true;
        if ((checkProjectResult!='noIncome' && checkProjectResult !='') && checkProjectResult == 'noProBudget' && projectClass == 'yfContract') {
			checkBudgetFlag = false;
		}

        if ((checkProjectResult!='noIncome' && checkProjectResult !='') && checkBudgetFlag) {
			if (checkProjectResult == 'cwIncomeClaim') {
				checkProjectInfo = "当前项目有未结束的认领经费，不能进行经费认领！";			
			} else if (checkProjectResult == 'alteration') {
				checkProjectInfo = "当前项目有未结束的调账经费，不能进行经费认领！";			
			} else if (checkProjectResult == 'claimBack') {
				checkProjectInfo = "当前项目有未结束的退回经费，不能进行经费认领！";				
			} else if (checkProjectResult == 'noProBudget') {
				checkProjectInfo = "当前项目没有登记预算，请补充预算后再经费认领！";
			}
			ElMessage.error(checkProjectInfo);	
            projectId = "";
            return false;	
		} 
        else{
            selectRef.value.blur();//符合条件后手动让el-select 失去焦点即可收起下拉框
            claimProjectShow.value.projectId = projectId;
            claimProjectShow.value.projectName = data.name;
            claimProjectShow.value.chargerName = data.chargerName; 
            claimShow.value.projectId = projectId;
            claimShow.value.projectName = data.name;
            claimFeeShow.value.projectClass = projectClass; 
            initClaimFeeInfo(projectId); //认领数据
            handleContract(projectClass);//横向项目处理
            if(projectClass == 'zXProject'){
                getCliamManageFee(projectId); //纵向项目才有管理费
            }
        }
    } catch (error) {
        console.log(error);
    }
}

// 选择项目后，自动初始化认领和项目相关的数据
const initClaimFeeInfo = async (projectId)=>{
    if (!projectId) {
        ElMessage.error("未选择要认领的项目！");
		return;
	}
    let params = {projectId:projectId,cwIncomeId:cwIncomeShow.value.id};
    try {
        const res = await getClaimFeeInfo(params);
        if (res.code == 200) {
            claimProjectShow.value.notIncomeFee = FloatDiv(res.data.notIncomeFee,10000); //项目未到账金额
            claimProjectShow.value.projectFeeInfo = res.data.projectFeeInfo;//项目合同金额展示信息
            claimFeeShow.value.canClaimFee = FloatDiv(res.data.canClaimFee,10000); //可认领金额
            claimFeeShow.value.claimFeeInfo = res.data.claimFeeInfo; //可认领多少
            claimFeeShow.value.planOutboundFee = FloatDiv(res.data.planOutboundFee,10000);//计划外拨
            claimFeeShow.value.outboundFee = FloatDiv(res.data.outboundFee,10000); //已外拨
            showclaimFee.value = true;//展示可认领多少金额提示
            claimFeeShow.value.feeSchemeId = res.data.feeSchemeId;//管理费提取方案id，固定值
            claimFeeShow.value.claimIncomeFeeShow = res.data.claimIncomeFeeShow; //经费卡号
            res.data.claimIncomeFeeShow.map(item =>{
                item.incomeFee= FloatDiv(item.incomeFee,10000);
                item.outboundFee= FloatDiv(item.outboundFee,10000);
                item.schoolFee= FloatDiv(item.schoolFee,10000);
            });
            claimFeeShow.value.claimIncomeFeeShow = res.data.claimIncomeFeeShow;

            cardShow.value = true; //选了项目后展示
            //留校预算是否已拆分标识,如果已拆分，则不在拆分 即只拆分一次
            //如果是拆分本次到账预算，则该值默认为false
            //该值等于true时，提交表单时无需填写预算，后台也无需接收预算，否则要校验提交表单时必须填写预算信息
            claimFeeShow.value.hasCardLiuxiaoBudget = res.data.hasCardLiuxiaoBudget;
            claimShow.value.budgetSplitModde = res.data.budgetSplitModde;//分割方式        
            showSplitIncomeFeeView();
        }
    }catch (error) {
        console.log(error);
    }
}

//显示经费卡拆分查看页面
const showSplitIncomeFeeView = ()=>{
    //有卡的情况：1.经费卡入账，budgetSplitModde ==chargerConfirm；
    // 2.认领入账：budgetSplitModde 是选了且不为chargerConfirm
    if (claimFeeShow.value.hasCardLiuxiaoBudget) {
        //2
        if (claimShow.value.budgetSplitModde != "chargerConfirm") {
            budgetSplitShow.value = false;
            budgetshow.value = true;
            getCliamIncomeBudget();
        }else{
            budgetSplitShow.value = true; 
            budgetshow.value= false;
            return;
        }
    }else{
        //没有卡的情况
        //横向项目，无项目预算，不展示预算
        if(claimFeeShow.value.projectClass == 'yfContract' && checkProjectResult =='noProBudget'){
            budgetSplitShow.value = false; 
        }else{
            budgetSplitShow.value = true; 
        }
        budgetshow.value= false;
        return;
    }
}

//选中分割方式
const handleSplitModde =(value) =>{
    claimShow.value.budgetSplitModde = value;
    budgetSplitShow.value = false;
    budgetshow.value = true;
    getCliamIncomeBudget(); 
}

//初始化预算科目
const getCliamIncomeBudget = async ()=>{
    var personIds = claimFeeShow.value.claimIncomeFeeShow.map(item => item.feeChargerId).join(",");
    let params={projectId:projectId,projectClass:claimFeeShow.value.projectClass,
        budgetSplitModde:claimShow.value.budgetSplitModde,personIds:personIds};
    try {
        const res = await getBudegt(params);
        if (res.code == 200) {
            res.data.map(item =>{
                item.subjectFee= FloatDiv(item.subjectFee,10000);
                item.claimSubBudgetFeeShow.map(items =>{
                    if(items.budgetFee !=''){
                        items.budgetFee = FloatDiv(items.budgetFee,10000);
                    }
                    items.splitBudgetFee = FloatDiv(items.splitBudgetFee,10000);
                })
            });
            claimFeeShow.value.claimBudgetFeeShow = res.data;
        }
    }catch (error) {
        console.log(error);
    }
}

//初始化管理费
const getCliamManageFee = async (projectId)=>{
    let params = {projectId:projectId};
    try {
        const res = await getManage(params);
        if (res.code == 200) {
            res.data.map(item =>{
                item.claimSubManageFee.map(items =>{
                    if(items.subjectFee !=''){
                        items.subjectFee = FloatDiv(items.subjectFee,10000);
                    }
                    items.splitManageFee = FloatDiv(items.splitManageFee,10000);
                })
            });
            claimFeeShow.value.claimManageFeeShow = res.data;
            manageShow.value = true;
        }
    }catch (error) {
        console.log(error);
    }
}

//横向项目处理:不体现来款类型、是否创建新卡；默认为混合经费
const handleContract = async (projectClass)=>{
    if (projectClass == 'yfContract') { // 横向项目
        showIncomeType.value = false;
        showNewCardFlag.value = false;
		claimShow.value.incomeType= "mixed";
	}
}

function checkfee(val){
    return ('' + val) // 第一步：转成字符串
    .replace(/[^0-9.]/g, '') //只保留数字和点
    .replace(/^0+(\d)/, '$1') // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
    .replace(/^\./, '0.'); // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
}

//检查认领经费
const checkclaimFee = (value)=>{
    if (projectId == "") {
        ElMessage.error("请先选择项目！");	
		claimShow.value.claimFee="";
		return false;
	}
    // if(!isNum(value)){
    //     ElMessage.error("请输入数字");
    //     claimShow.value.claimFee = "";
    //     return false;
    // }
    value=checkfee(value);
    claimShow.value.claimFee=value;
    if (value > 100000) {
        ElMessage.error("单笔金额不能超过10亿");
        claimShow.value.claimFee = "";
        return false;
    }
    
    if (!isMoney(value)) {
        ElMessage.error("金额小数位不能超过6位，只能精确到分");	
        claimShow.value.claimFee="";
		return false;
    } 
    if (Number(value) > Number(claimFeeShow.value.canClaimFee)) {
        ElMessage.error('认领金额不能超过'+(Number(claimFeeShow.value.canClaimFee))+'万元！');	
		claimShow.value.claimFee="";
		return false;
	}
    claimShow.value.schoolFee = value!=''?value:0;
    claimFeeShow.value.claimIncomeFeeShow[0].schoolFee= claimShow.value.schoolFee;
    if (claimFeeShow.value.projectClass == 'zXProject') {
        claimFeeShow.value.claimManageFeeShow.map(item => {
            if (item.subjectName != "") {
                item.claimSubManageFee.map(items => {
                    if (value != null && value != '') {
                        items.subjectFee = FloatMul(value,0.05);
                    } else {
                        items.subjectFee = 0;
                    }
                })
            }
        });
    }
}

//检查外拨经费
const checkoutboundFee = (value)=>{
    // if(!isNum(value)){
    //     ElMessage.error("请输入数字");
    //     claimShow.value.outboundFee = "";
    //     return false;
    // }
    if (projectId == "") {
        ElMessage.error("请先选择项目！");	
		claimShow.value.outboundFee="";
		return false;
	}
    value=checkfee(value);
    claimShow.value.outboundFee=value;
    if (value > 100000) {
        ElMessage.error("单笔金额不能超过10亿");
        claimShow.value.outboundFee = "";
        return false;
    }
    
    if (!isMoney(value)) {
        ElMessage.error("金额小数位不能超过6位，只能精确到分");	
        claimShow.value.outboundFee="";
		return false;
    } 
    var canOutboundFee = FloatSub(claimFeeShow.value.planOutboundFee,claimFeeShow.value.outboundFee); // 可外拨金额
    if (Number(value) > Number(canOutboundFee)) {
		ElMessage.error("外拨金额不能超过"+canOutboundFee+"万元！");	
        claimShow.value.outboundFee="";
		return false;
	}
    if (Number(value) > Number(claimShow.value.claimFee)) {
		ElMessage.error("外拨金额不能超过认领金额！");	
        claimShow.value.outboundFee="";
		return false;
	}
    claimShow.value.schoolFee= FloatSub(claimShow.value.claimFee,value);
    claimFeeShow.value.claimIncomeFeeShow[0].outboundFee = value;
    claimFeeShow.value.claimIncomeFeeShow[0].schoolFee= claimShow.value.schoolFee;
}

//检查留校金额
const checkSchoolFeeForm = (value)=>{
    var checkResult = true;
    if (Number(value) < 0) {
        ElMessage.error("留校金额不能为负数！");
		checkResult = false;
		return false;
	}
    if (!checkResult) {
		return false;
	}
    // 可到账留校总金额 = 项目未到账金额 - (计划外拨金额 - 项目已外拨金额)
    var canSchoolFee = FloatSub(claimProjectShow.value.notIncomeFee,FloatSub(claimFeeShow.value.planOutboundFee,claimFeeShow.value.outboundFee));
    if (Number(value) > Number(canSchoolFee)) {
        ElMessage.error('留校总额不能超过'+canSchoolFee+'万元！');
		return false;
	}
	
	return true;
}

//本次入账金额填写校验
const checkbudgetFee = (item,items)=>{
    item.budgetFee=checkfee(item.budgetFee);
    var value = item.budgetFee;
    if (Number(value) < 0) {
        ElMessage.error("本次入账金额不能为负数！");
        item.budgetFee= 0;
        sumbudgetFee();
        updateParentBudget();
		return false;
	}
    if (!isMoney(value)) {
        ElMessage.error("金额小数位不能超过6位，只能精确到分");	
        item.budgetFee= 0;
        sumbudgetFee();
        updateParentBudget();
		return false;
    }
    var subjectSchoolFee = Number(items.subjectFee);
    // 当前预算科目的合计 = 本次入账金额合计 + 已入账金额合计
    var curBudgetFeeTotal = FloatAdd(parseFloat(value),parseFloat(item.splitBudgetFee));
    var subjectName = items.subjectName;
    if (Number(curBudgetFeeTotal) > Number(subjectSchoolFee)) {
		ElMessage.error("科目【"+subjectName+"】的合计超过了该科目的留校总额度金额，请修改！");
        item.budgetFee = 0;
        sumbudgetFee();
         updateParentBudget();
		return false;
	}
    updateParentBudget();
    sumbudgetFee();
};

const updateParentBudget=()=>{
    // 构建父节点到子节点的映射
    const parentMap = new Map();
    claimFeeShow.value.claimBudgetFeeShow.forEach(node => {
        if(node.subjectName != "合计"){const parentCode = node.subjectUpCode;
        if (!parentMap.has(parentCode)) {
            parentMap.set(parentCode, []);
        }
        parentMap.get(parentCode).push(node);}
    });

    // 找到所有根节点（subjectUpCode为null）并进行处理
    claimFeeShow.value.claimBudgetFeeShow.filter(node => node.subjectUpCode === null && node.subjectName != "合计")
        .forEach(root => calculateBudget(root,parentMap));
}

//递归计算并更新父节点的预算费用
const calculateBudget=(node,parentMap)=> {
        const children = parentMap.get(node.subjectCode) || [];
        if (children.length > 0) {
            let sum = 0;
            children.forEach(child => {
                calculateBudget(child,parentMap); // 先递归处理子节点
                child.claimSubBudgetFeeShow.map(vals => {
                    sum =FloatAdd(sum, parseFloat(Number(vals.budgetFee)));
                })
            });
            node.claimSubBudgetFeeShow.map(vals => {
                vals.budgetFee =sum;// 更新当前节点的预算
            })
        }
        // 无子节点则保持原值
}

//本次入账计算合计
const sumbudgetFee =()=>{
    claimFeeShow.value.claimBudgetFeeShow.map(item => {
        if (item.subjectName == "合计" ) {
            item.claimSubBudgetFeeShow.map(val =>{
                val.budgetFee=0;
                claimFeeShow.value.claimBudgetFeeShow.map(items => {
                    if (items.subjectName != '合计' && items.hasChildren == '0') {
                        items.claimSubBudgetFeeShow.map(vals => {
                            if (val.feeChargerId == vals.feeChargerId && vals.budgetFee !="") {
                                //val.budgetFee +=parseFloat(Number(vals.budgetFee));
                                val.budgetFee =FloatAdd(val.budgetFee, parseFloat(Number(vals.budgetFee)));
                            }
                        })
                    }
                })
            })           
        }
    });
}
//保存前验证及处理数据
const beforesave = ()=>{
    let flag = true;
    if (!projectId) {
        ElMessage.error("未选择要认领的项目！");
		flag= false;
	}
   if(Number(claimShow.value.claimFee) <=0){
        ElMessage.error("请填写认领金额！");
		flag=  false;
   }
    //横向项目
    if (claimFeeShow.value.projectClass == 'yfContract' ) {
        //无项目预算，不校验
        if (checkProjectResult == 'noProBudget') {
            
        }
        //有项目，未选择额度拆分方式，不校验
        if (budgetSplitShow.value && claimShow.value.budgetSplitModde == 'chargerConfirm') {
           
        }
    }

   if (claimFeeShow.value.projectClass != 'yfContract' && budgetSplitShow.value && claimShow.value.budgetSplitModde == 'chargerConfirm') { 
		ElMessage.error("您还没有拆分额度，请确认额度拆分方式！");
		flag=  false;
	}
    
    checkSchoolFeeForm(claimShow.value.schoolFee);
    if(claimShow.value.budgetSplitModde == 'incomeBudgetSplit'){
        var total = 0;
        claimFeeShow.value.claimBudgetFeeShow.find(item=> {
            if (item.subjectName == "合计") {
                total= item.claimSubBudgetFeeShow[0].budgetFee;
            }
        })
        if(Number(total) != Number(claimShow.value.schoolFee)){
            ElMessage.error('本次入账留校金额不等于本次额度拆分合计，请修改！');
            flag=  false;
        }
    }
    return flag;
}
//处理金额
const handleMoney =(params)=>{
    params.claimShow.claimFee = FloatMul(params.claimShow.claimFee,10000);
    params.claimShow.outboundFee = FloatMul(params.claimShow.outboundFee,10000);
    params.claimShow.schoolFee = FloatMul(params.claimShow.schoolFee,10000);
    params.claimFeeShow.claimIncomeFeeShow.map(item => {
        item.incomeFee = FloatMul(item.incomeFee,10000);
        item.outboundFee = FloatMul(item.outboundFee,10000);
        item.schoolFee = FloatMul(item.schoolFee,10000);
    });
    if (params.claimFeeShow.claimBudgetFeeShow != null) {
        params.claimFeeShow.claimBudgetFeeShow.map(item => {
            item.subjectFee = FloatMul(item.subjectFee, 10000);
            item.claimSubBudgetFeeShow.map(items => {
                if (items.budgetFee != '') {
                    items.budgetFee = FloatMul(items.budgetFee, 10000);
                }
                items.splitBudgetFee = FloatMul(items.splitBudgetFee, 10000);
            })
        });
    }
    if (params.claimFeeShow.projectClass == 'zXProject') {
        params.claimFeeShow.claimManageFeeShow.map(item => {
            item.claimSubManageFee.map(items => {
                items.subjectFee = FloatMul(items.subjectFee, 10000);
                items.splitManageFee = FloatMul(items.splitManageFee, 10000);
            })
        });
    } 
}

//点击保存
const save = async(status) => {
  try {
    let flag = beforesave();//保存前校验
      if (flag) {
          let claimShowNew = JSON.parse(JSON.stringify(claimShow.value));
          let claimFeeShowNew = JSON.parse(JSON.stringify(claimFeeShow.value));
          const params = { claimShow: claimShowNew, claimFeeShow: claimFeeShowNew };
          params.claimShow.status = status;
          handleMoney(params);
          proxy.$modal.loading("请稍候...");
          const res = await addclaim(params);
          proxy.$modal.closeLoading();
          if (res.code === 200) {
              ElMessage({ message: "操作成功！", type: "success", });
              dialogVisible.value = false;
              handleclear();
              emit("save-success");
          }
      }
  } catch (error) {
    proxy.$modal.closeLoading();
    console.log(error);
  }
};

//关闭弹窗
const handleClose = () => {
  //重置表单数据
  handleclear();
};
</script>

<style scoped lang="scss">
@import url("@/views/fee/index.scss");

</style>